package com.caiheng.api.service.examine.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.dao.examine.ExamineApproveMapper;
import com.caiheng.api.dao.examine.ExamineApproveRegAdminRecordMapper;
import com.caiheng.api.dao.examine.ExamineApproveRegRecordMapper;
import com.caiheng.api.dao.examine.ExamineApproveTemplateUserMapper;
import com.caiheng.api.entity.examine.*;
import com.caiheng.api.entity.wxmsg.WxTemplate;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.exception.TransactionalException;
import com.caiheng.api.service.base.impl.BaseServiceImpl;
import com.caiheng.api.service.examine.ExamineApproveRegAdminRecordService;
import com.caiheng.api.service.examine.ExamineApproveTemplateUserService;
import com.caiheng.api.service.platfom.WxTemplateService;
import com.caiheng.api.service.wxuser.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 审批流程记录的 审核人员处理记录Service业务层处理
 *
 * @author ruoyi
 * @date 2022-11-24
 */
@Service
public class ExamineApproveRegAdminRecordServiceImpl extends BaseServiceImpl<ExamineApproveRegAdminRecordMapper, ExamineApproveRegAdminRecord> implements ExamineApproveRegAdminRecordService {

    @Resource
    private ExamineApproveRegAdminRecordMapper approveRegAdminRecordMapper;
    @Resource
    private ExamineApproveTemplateUserMapper approveTemplateUserMapper;
    @Resource
    private ExamineApproveMapper approveMapper;
    @Resource
    private ExamineApproveTemplateUserService approveTemplateUserService;
    @Resource
    private ExamineApproveRegRecordMapper approveRegRecordMapper;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private UserService userService;

    @Override
    @Transactional
    public int handleRecord(User user, ExamineApproveRegRecord regRecord, ExamineApproveRegAdminRecord adminRecord) {
        int ret = 0;
        try{
            adminRecord.setHandleTime(new Date());
            //处理当前审批记录
            ret = approveRegAdminRecordMapper.updateById(adminRecord);

            //审批通过，继续下一步
            if(adminRecord.getState() == 1){
                ExamineApprove examineApprove = approveMapper.selectById(regRecord.getApproveId());
                if(examineApprove != null){
                    QueryWrapper<ExamineApproveTemplateUser> qw = new QueryWrapper<>();
                    qw.eq("template_id",examineApprove.getTemplateId());
                    qw.eq("state", 1);
//                    qw.eq("is_copy", 0);
                    qw.eq("duty_index", adminRecord.getHandleSort());
                    qw.last("limit 1");
                    ExamineApproveTemplateUser templateUser = approveTemplateUserMapper.selectOne(qw);
                    if(templateUser != null){
                        if(templateUser.getIsEnd() == 0){
                            ExamineApproveRegAdminRecord regAdminRecord = new ExamineApproveRegAdminRecord();

                            //是否已经存在处理记录
                            QueryWrapper<ExamineApproveRegAdminRecord> qwExist = new QueryWrapper<>();

                            QueryWrapper<ExamineApproveTemplateUser> qwNext = new QueryWrapper<>();
                            qwNext.eq("template_id",examineApprove.getTemplateId());
                            qwNext.eq("state", 1);
//                            qwNext.eq("is_copy", 0);
                            qwNext.eq("duty_index", adminRecord.getHandleSort() + 1);
                            qwNext.last("limit 1");
                            ExamineApproveTemplateUser templateUserNext = approveTemplateUserMapper.selectOne(qwNext);
                            if(templateUserNext!= null){
                                regAdminRecord.setUserId(templateUserNext.getUserId());
                                regAdminRecord.setTemplateUserId(templateUserNext.getId());

                                //是否已经存在处理记录
                                qwExist.eq("template_user_id", templateUserNext.getId());
                                qwExist.eq("user_id", templateUserNext.getUserId());
                            }

                            regAdminRecord.setCreateTime(new Date());
                            regAdminRecord.setApproveRecordId(regRecord.getId());
                            regAdminRecord.setState(0);
                            regAdminRecord.setTemplateId(examineApprove.getTemplateId());
                            regAdminRecord.setHandleSort(adminRecord.getHandleSort() + 1);

                            qwExist.eq("approve_record_id", regRecord.getId());
                            qwExist.eq("template_id", examineApprove.getTemplateId());
                            qwExist.eq("handle_sort", adminRecord.getHandleSort() + 1);
                            qwExist.last("limit 1");
                            //是否已经存在处理记录
                            ExamineApproveRegAdminRecord oldRecord = approveRegAdminRecordMapper.selectOne(qwExist);
                            if(oldRecord == null){
                                ret = approveRegAdminRecordMapper.insert(regAdminRecord);
                                if(ret <= 0){
                                    throw new TransactionalException("approveRegInfoMapper insert error");
                                }
                            }

                            //给当前用户发送推送消息
                            wxTemplateService.sendWxMsgExamineApproveToNext(examineApprove, templateUserNext, regRecord, regAdminRecord, 0);

                            if(regRecord.getState() == 0){//待处理的情况，要修改成处理中
                                regRecord.setState(1);
                            }

                            ret = approveRegRecordMapper.updateById(regRecord);
                            if(ret <= 0){
                                throw new TransactionalException("approveRegRecordMapper updateById error");
                            }
                        } else {//最后一个  直接发送推送
                            //审批状态  0 - 未处理  1 - 审批同意  2 - 审批拒绝
                            int state = adminRecord.getState();
                            String content = adminRecord.getContent();
                            System.out.println("审核人员审核结果：" + content);
                            //state 审批的状态 0 - 待审批  1 - 审批中  2 - 审核通过  3 - 撤销审批 4 - 审核拒绝
                            if(state == 1){
                                regRecord.setState(2);
                            }else{
                                regRecord.setState(4);
                            }
                            regRecord.setCheckResult(content);
                            regRecord.setCheckOverTime(new Date());
                            ret = approveRegRecordMapper.updateById(regRecord);
                            if(ret <= 0){
                                throw new TransactionalException("approveRegRecordMapper updateById error");
                            }

                            //抄送消息给 抄送人
                            List<ExamineApproveTemplateUser> copyUserList = approveTemplateUserService.getCopyUserList(examineApprove.getTemplateId());
                            if(CollUtil.isNotEmpty(copyUserList)){
                                for (ExamineApproveTemplateUser copyUser : copyUserList){
                                    //给推送人员发送抄送信息
                                    wxTemplateService.sendWxMsgExamineApprove(examineApprove, copyUser, regRecord, adminRecord,1);
                                }
                            }
                            User userRecord = userService.findById(regRecord.getUserId());
                            //发送给用户 推送消息  审批已完成
                            wxTemplateService.sendWxMsgExamineApproveToUser(examineApprove, userRecord, regRecord);
                        }
                    }
                }
            } else if(adminRecord.getState() == 2){
                //审批驳回

                //state 审批的状态 0 - 待审批  1 - 审批中  2 - 审核通过  3 - 撤销审批 4 - 审核拒绝
                regRecord.setState(4);
                regRecord.setCheckResult(adminRecord.getContent());
                regRecord.setCheckOverTime(new Date());
                ret = approveRegRecordMapper.updateById(regRecord);
                if(ret <= 0){
                    throw new TransactionalException("approveRegRecordMapper updateById error");
                }

            }

        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("approveRegInfoMapper insert error");
        }
        return ret;
    }
}
